package com.cehome.cloudbox.enums;

import java.sql.Timestamp;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

public enum ClockPool {
    INSTANCE(1L);

    private final long period;
    private final AtomicLong nowTime;
    private boolean started = false;
    private ScheduledExecutorService executorService;

    private ClockPool(long period) {
        this.period = period;
        this.nowTime = new AtomicLong(System.currentTimeMillis());
    }

    public void initialize() {
        if (!this.started) {
            this.executorService = new ScheduledThreadPoolExecutor(1, (r) -> {
                Thread thread = new Thread(r, "system-clock");
                thread.setDaemon(true);
                return thread;
            });
            this.executorService.scheduleAtFixedRate(() -> {
                this.nowTime.set(System.currentTimeMillis());
            }, this.period, this.period, TimeUnit.MILLISECONDS);
            Runtime.getRuntime().addShutdownHook(new Thread(this::destroy));
            this.started = true;
        }
    }

    public long currentTimeMillis() {
        return this.started ? this.nowTime.get() : System.currentTimeMillis();
    }

    public String currentTime() {
        return (new Timestamp(this.currentTimeMillis())).toString();
    }

    public void destroy() {
        if (this.executorService != null) {
            this.executorService.shutdown();
        }

    }
}
